//
//  AppDelegate.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/11/22.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabbarViewController.h"
//#import "LoginViewController.h"
#import "ShopcartOrderViewController.h"
#import "MineOrderViewController.h"
#import "OrderDetailViewController.h"
//#import "OrderModel.h"
#import "MineRefundListViewController.h"
#import "RefundDetailViewController.h"
#import "PayStatusViewController.h"
#import "NotificationViewController.h"
#import "MessageModel.h"
//#import "EditSendViewController.h"
//#import "OthersMemberInfoModel.h"
//#import "RCDLinkerMessage.h"
//#import "IntroViewController.h"
#import "HomeViewController.h"
#import "MineViewController.h"
#import <AlipaySDK/AlipaySDK.h>

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#import <WXApi.h>

@interface AppDelegate ()<JPUSHRegisterDelegate,UNUserNotificationCenterDelegate,QYConversationManagerDelegate>
{
    BMKMapManager *_mapManager;
}

@end

@implementation AppDelegate

- (instancetype)init {
    self = [super init];
    if (self) {
        // 获取本地用户信息
        [[UserInfo shareInstance] getUserModel];
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //NSLog(@"%d,%@",IsProduction,RongCloud_Key);
    // 设置所有textField的光标颜色
    [[UITextField appearance] setTintColor:[UIColor ThemeColor]];
    if  (![WXApi registerApp:Wechat_Key]){
        NSLog(@"注册微信失败");
    };
    
    
    // 设置APNS
    [self setAPNS];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:@"AppStore"
                 apsForProduction:IsProduction];
    
    //    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    //    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    
    
    // 更新用户信息
    [self getUserInterfaceModel];
    
    // 获取分类
    [[ClassifyManager shareInstance] setupAllClassify];
    
    // 设置网易七鱼
    [self setQiYu];
    
    // 设置百度地图
    [self setBaiduMap];
    
    // 启动图片延时
    [NSThread sleepForTimeInterval:2];
    
    [self setupTabbarVC];
    return YES;
}

#pragma mark - Private Method
- (void)setupTabbarVC {
    
    BaseTabbarViewController *tabbar = [[BaseTabbarViewController alloc] init];
    self.window.rootViewController = tabbar;
    
    //    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isFirst"]) {
    //        IntroViewController *introVC = [[IntroViewController alloc] init];
    //        self.window.rootViewController = introVC;
    //    } else {
    //        BaseTabbarViewController *tabbar = [[BaseTabbarViewController alloc] init];
    //        self.window.rootViewController = tabbar;
    //    }
    
    //    if ([UserInfo shareInstance].isLogin) {
    //        BaseTabbarViewController *tabbar = [[BaseTabbarViewController alloc] init];
    //        self.window.rootViewController = tabbar;
    //    } else {
    //        LoginViewController *login = [[LoginViewController alloc] init];
    //        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
    //        self.window.rootViewController = nav;
    //    }
}

- (void)setAPNS {
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}
- (void)getUserInterfaceModel {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([UserInfo shareInstance].isLogin) {
            [[UserInfo shareInstance] updateUserInterfaceModel:^(BOOL success) {
                [JPUSHService setAlias:[UserInfo shareInstance].user.mid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                    NSLog(@"alias %@",iAlias);
                } seq:[UserInfo shareInstance].user.mid.integerValue];
            }];
        }
    });
}

- (void)notificationHandling:(NSDictionary *)userInfo {
    // 有推送就显示，只有点击首页小信封图标才消除
    [self receiveNewMessage];
    
    UIViewController *vc = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
    if ([vc isKindOfClass:[HomeViewController class]]) {
        [vc viewWillAppear:NO];
    }
    if ([vc isKindOfClass:[MineViewController class]]) {
        [vc viewWillAppear:NO];
    }
    
    // 调用已读接口
    [self uploadSaveInfomation:[userInfo safeObjectForKey:@"iid"]];
    // 根据类型跳转界面 消息类型（1发货，2退款）（哈哈文玩：1发货，2退款，3发货，4已退款，5系统消息，6退款驳回）
    switch ([[userInfo safeObjectForKey:@"itype"] integerValue]) {
//        case 1:
//        {
//            /*
//             // 去发货
//             EditSendViewController *editSendVC = [[EditSendViewController alloc] init];
//             OrderModel *temp = [[OrderModel alloc] init];
//             temp.osid = [userInfo safeObjectForKey:@"omid"];
//             editSendVC.detailModel = temp;
//             [vc.navigationController pushViewController:editSendVC animated:YES];
//             */
//        } break;
        case 1:
        {
            OrderModel *temp = [[OrderModel alloc] init];
            temp.omid = [userInfo safeObjectForKey:@"omid"];
            OrderDetailViewController *orderDetailVC = [[OrderDetailViewController alloc] init];
            orderDetailVC.detailModel = temp;
            orderDetailVC.fromType = FromTypeSelfOrder;
            [vc.navigationController pushViewController:orderDetailVC animated:YES];
        } break;
        case 2:
        {
            OrderModel *temp = [[OrderModel alloc] init];
            temp.ogid = [userInfo safeObjectForKey:@"ogid"];
            RefundDetailViewController *orderDetailVC = [[RefundDetailViewController alloc] init];
            orderDetailVC.detailModel = temp;
            [vc.navigationController pushViewController:orderDetailVC animated:YES];
            
        } break;
        case 5:
        {
            MessageSystemModel *model = [[MessageSystemModel alloc] init];
            model.iid = [userInfo safeObjectForKey:@"iid"];
            model.ititle = [userInfo safeObjectForKey:@"title"];
            model.icontent = [userInfo safeObjectForKey:@"content"];
            model.itype = [userInfo safeObjectForKey:@"itype"];
            model.createtime = [userInfo safeObjectForKey:@"createtime"];
            model.remark = [userInfo safeObjectForKey:@"omid"];
            model.istatus = YES;
            
            NotificationViewController *notificationVC = [[NotificationViewController alloc] init];
            notificationVC.detailModel = model;
            [vc.navigationController pushViewController:notificationVC animated:YES];
        } break;
        default:
            break;
    }
}
- (void)receiveNotificationHandler:(NSDictionary *)userInfo {
    // 有推送就显示，只有点击首页小信封图标才消除
    [self receiveNewMessage];
    
    UIViewController *vc = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
    if ([vc isKindOfClass:[HomeViewController class]]) {
        [vc viewWillAppear:NO];
        return;
    }
    if ([vc isKindOfClass:[MineViewController class]]) {
        [vc viewWillAppear:NO];
        return;
    }
    //（1发货，2退款）
    switch ([[userInfo safeObjectForKey:@"itype"] integerValue]) {
        case 1:
        {
            if ([vc isKindOfClass:[MineOrderViewController class]]) {
                [(MineOrderViewController *)vc reloadData];
            } else if ([vc isKindOfClass:[OrderDetailViewController class]]) {
                if ([((OrderDetailViewController *)vc).detailModel.omid isEqualToString:[userInfo safeObjectForKey:@"omid"]]) {
                    [(OrderDetailViewController *)vc getNetData];
                }
            }
        } break;
        case 2:
        {
            if ([vc isKindOfClass:[MineRefundListViewController class]]) {
                [(MineRefundListViewController *)vc getNetData];
            } else if ([vc isKindOfClass:[RefundDetailViewController class]]) {
                if ([((RefundDetailViewController *)vc).detailModel.ogid isEqualToString:[userInfo safeObjectForKey:@"ogid"]]) {
                    [(RefundDetailViewController *)vc getNetData];
                }
            }
        } break;
        default:
            break;
    }
    
}
- (void)uploadSaveInfomation:(NSString *)iid {
    if (TextIsNotNil(iid)) {
        [MBProgressHUD showHUDProgress:self.window animated:YES];
        [MYAFNetworking POST:URL_Save_Information parameters:@{@"iid":iid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            [MBProgressHUD hideHUDForView:self.window animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            [MBProgressHUD hideHUDForView:self.window animated:YES];
        }];
    }
}

- (void)updateBadgeValue:(BOOL)showBadge {
    BaseTabbarViewController *tabbar = (BaseTabbarViewController *)self.window.rootViewController;
    [tabbar updateBadge:showBadge];
}
- (void)receiveNewMessage {
    [UserInfo shareInstance].user.showBadge = YES;
    [[UserInfo shareInstance] updateUserModel];
    [[NSNotificationCenter defaultCenter] postNotificationName:ReciveRongCloudMessage object:nil];
}
#pragma mark - 网易七鱼
- (void)setQiYu {
    [[QYSDK sharedSDK] registerAppId:QiYuAppKey appName:QiYuAppName];
    QYConversationManager *manager = [[QYSDK sharedSDK] conversationManager];
    [manager setDelegate:self];
}
#pragma mark QYConversationManagerDelegate
- (void)onUnreadCountChanged:(NSInteger)count {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (count > 0) {
            [self receiveNewMessage];
        }
    });
}
- (void)onReceiveMessage:(QYMessageInfo *)message {
    
}
#pragma mark - 百度地图
- (void)setBaiduMap {
    _mapManager = [[BMKMapManager alloc] init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:BaiduMapKey generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
}

#pragma mark - APNS
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    [[QYSDK sharedSDK] updateApnsToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self receiveNewMessage];
        
        [self receiveNotificationHandler:notification.request.content.userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self notificationHandling:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    [self receiveNotificationHandler:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
    [self notificationHandling:userInfo];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    return [self handleUrl:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [self handleUrl:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [self handleUrl:url];
}

- (BOOL)handleUrl:(NSURL *)url {
    if ([[url absoluteString] rangeOfString:[NSString stringWithFormat:@"%@://pay",Wechat_Key]].location == 0) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    /*
     //判断如果是支付的话  不走友盟方法  直接走微信和QQ的方法
     if([[url absoluteString] rangeOfString:[NSString stringWithFormat:@"%@://pay",UMeng_Wechat_Key]].location == 0)
     
     return [WXApi handleOpenURL:url delegate:self];
     
     else
     
     return [[UMSocialManager defaultManager] handleOpenURL:url];
     */
    if ([url.host isEqualToString:@"safepay"] || [url.host isEqualToString:@"platformapi"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            UIViewController *topVC = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
            NSString *osid;
            if ([topVC isKindOfClass:[ShopcartOrderViewController class]]) {
                osid = ((ShopcartOrderViewController *)topVC).osid;
            } else if ([topVC isKindOfClass:[OrderDetailViewController class]]) {
                osid = ((OrderDetailViewController *)topVC).omid;
            } else if ([topVC isKindOfClass:[MineOrderViewController class]]) {
                osid = ((MineOrderViewController *)topVC).omid;
            }
            if (TextIsNotNil(osid)) {
                PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
                statusVC.osid = osid;
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    statusVC.type = StatusTypePaySuccess;
                } else {
                    statusVC.type = StatusTypePayFail;
                }
                
                [topVC.navigationController pushViewController:statusVC animated:YES];
            }
            
        }];
        
//        // 授权跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//            // 解析 auth code
//            NSString *result = resultDic[@"result"];
//            NSString *authCode = nil;
//            if (result.length>0) {
//                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
//                for (NSString *subResult in resultArr) {
//                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
//                        authCode = [subResult substringFromIndex:10];
//                        break;
//                    }
//                }
//            }
//            NSLog(@"授权结果 authCode = %@", authCode?:@"");
//        }];
    } else if ([[url absoluteString] rangeOfString:[NSString stringWithFormat:@"%@://",Wechat_Key]].location == 0){
        
//        return [WXApi handleOpenURL:url delegate:self];
    } else {
        // 三方登录
        
    }
    return YES;
}

 //微信回调
 -(void)onResp:(BaseResp*)resp {
 if ([resp isKindOfClass:[PayResp class]]){
 __weak typeof(UIViewController *) weakSelf = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
 NSString *osid;
 if ([weakSelf isKindOfClass:[ShopcartOrderViewController class]]) {
 osid = ((ShopcartOrderViewController *)weakSelf).osid;
 } else if ([weakSelf isKindOfClass:[OrderDetailViewController class]]) {
     osid = ((OrderDetailViewController *)weakSelf).omid;
 } else if ([weakSelf isKindOfClass:[MineOrderViewController class]]) {
     osid = ((MineOrderViewController *)weakSelf).omid;
 }
 if (TextIsNotNil(osid)) {
 PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
 statusVC.osid = osid;
 PayResp *response=(PayResp *)resp;
 switch(response.errCode){
 case WXSuccess:
 //服务器端查询支付通知或查询API返回的结果再提示成功
 NSLog(@"支付成功");
 //                    if (((ShopcartOrderViewController *)weakSelf).block) {
 //                        ((ShopcartOrderViewController *)weakSelf).block(YES);
 //                    }
 //[((ShopcartOrderViewController *)weakSelf) disMissSelf];
 statusVC.type = StatusTypePaySuccess;
 break;
 default:
 //[MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"支付失败" animated:YES];
 NSLog(@"支付失败，retcode=%d",resp.errCode);
 statusVC.type = StatusTypePayFail;
 break;
 }
 
 [weakSelf.navigationController pushViewController:statusVC animated:YES];
 }
 }
 }


- (void)didReceiveMessageNotification:(NSNotification *)notification {
    /*
     NSNumber *left = [notification.userInfo objectForKey:@"left"];
     if ([RCIMClient sharedRCIMClient].sdkRunningMode ==
     RCSDKRunningMode_Background &&
     0 == left.integerValue) {
     int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE)]];
     //        [UIApplication sharedApplication].applicationIconBadgeNumber = unreadMsgCount;
     }
     */
}

#pragma mark - Method
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService resetBadge];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
